//
//  KCHttpRequest.m
//  Jade
//
//  Created by king on 16/6/24.
//  Copyright © 2016年 KC. All rights reserved.
//

#import "KCHttpRequest.h"
#import "AFNetworking.h"
#import "AppDelegate.h"

@implementation KCHttpRequest

+ (void)get:(NSString *)url :(requestKC)requestKC {
    
    //防抓包
    if ([self checkWebDelegate]) {
        requestKC(nil);
        return;
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 30.0f;
    [session GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        requestKC(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestKC(nil);
    }];
    
}

+ (void)post:(NSString *)url :(NSDictionary *)data :(requestKC)requestKC {
    
    //防抓包
    if ([self checkWebDelegate]) {
        requestKC(nil);
        return;
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 30.0f;
    
    [session POST:url parameters:data headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        requestKC(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestKC(nil);
    }];
    
}

+ (void)uploadImage:(NSString *)url :(NSDictionary *)data :(NSArray *)imageDataArray :(requestKC)requestKC{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 30.0f;
    [session setSecurityPolicy:[self customSecurityPolicy]];
    
    NSMutableDictionary *diction = [NSMutableDictionary dictionaryWithDictionary:data];
//    if (data[@"token"]) {
//        session.requestSerializer = [AFJSONRequestSerializer serializer];
//        [session.requestSerializer setValue:data[@"token"] forHTTPHeaderField:@"Y-Token"];
//        [diction removeObjectForKey:@"token"];
//    }
    
    [session POST:url parameters:diction headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        /*
         第一个参数：将要上传的数据的原始路径
         第二个参数：要上传的路径的key
         第三个参数：上传后文件的别名
         第四个参数：原始图片的格式
         */
        int8_t imageNum = 0;
        for (NSData *imageData in imageDataArray) {
            [formData appendPartWithFileData:imageData
                                        name:[NSString stringWithFormat:@"photo%d",imageNum]
                                    fileName:[NSString stringWithFormat:@"imageFile%d.jpg",imageNum]
                                    mimeType:@"image/jpg"];
            imageNum++;
            
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        requestKC(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestKC(nil);
    }];
    
}

+ (AFSecurityPolicy *)customSecurityPolicy {
    
    // 先导入证书 证书由服务端生成，具体由服务端人员操作
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"app.icangyu.com_bundle" ofType:@"cer"];//证书的路径
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES;
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil, nil];
    
    return securityPolicy;
}

//检查是否有代理-防抓包
+ (BOOL)checkWebDelegate{
    
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com&quot;"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = proxies[0];
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        return NO;
    }
    return YES;
    
}


@end
